import React, { PureComponent } from 'react';
import _ from 'lodash';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Select, Input, Checkbox, Tooltip, Spin } from 'antd';
import { PrimaryGhostC, FirstHeaderC, SecondHeaderC, InputC, PrimaryC, SelectC, TreeSelectC, TableC, DATA_ENTRY, AdvancedSearch, FixedButtonC } from '../../../comps';
const FormItem = Form.Item;
import { depCopy, findItemByKey } from '../../../utils/utils';
import myStyle from './myStyle.less';
import OperatorC from './operatorC';
import { connect } from 'dva';
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 6, offset: 0 },
    sm: { span: 7, offset: 0 },
    md: { span: 7, offset: 0 },
    lg: { span: 7, offset: 0 },
    xl: { span: 7, offset: 0 },
    xxl: { span: 7, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 16, offset: 0 },
    sm: { span: 15, offset: 0 },
    md: { span: 15, offset: 0 },
    lg: { span: 15, offset: 0 },
    xl: { span: 15, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};
@Form.create()
@connect(({ userManageNewM, loading, userM: user }) => ({ userManageNewM, loading, user }))
export default class OperatePageC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      cpTotal: 0, //关联组合表格的total
      cpCurrentPage: 1, //关联组合表格的currentPage
      cpNumInPage: 10, //关联组合表格的numInpage
      searchText: '',
      searchedColumn: '',
      changeDisable: true, // 租户信息的disable
      isCpReset: true, // 关联组合是否重置
      filteredData: [], // 关联组合筛选后的数据
      querySelectAllChecked: false, //关联组合 查询权限 全选控制
      operationSelectAllChecked: false, //关联组合 操作权限 全选控制
    };
  }
  componentDidMount() {
    this.props.onRef(this);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 主页面更改关联组合 状态
  onChangestate = (queryE, operationE) => {
    this.setState({
      querySelectAllChecked: queryE, //关联组合 查询权限 全选控制
      operationSelectAllChecked: operationE, //关联组合 操作权限 全选控制
    });
  };
  // 返回主页面
  onBack = (type) => {
    this.setState({
      cpCurrentPage: 1, //关联组合表格的currentPage
      cpNumInPage: 10, //关联组合表格的numInpage
      isCpReset: true, // 关联组合是否重置
      filteredData: [], // 关联组合筛选后的数据
    });
    this.props.onBack(false, type);
    this.cpRef.props.form.resetFields();
    this.onResetForm();
  };
  // 重置form表单事件
  onResetForm = () => {
    this.setState({
      changeDisable: true,
    });
    this.props.form.resetFields();
  };
  // 处理关联组合数据格式
  flatten2 = (tree) => {
    var arr = [];
    function spread(tree, pid) {
      for (var i = 0; i < tree.length; i++) {
        let item = tree[i];
        let { key, queryPermission, operationPermission } = item;
        let id = key;
        arr.push({ id, queryPermission, operationPermission });
        if (item.children && item.children.length > 0) {
          spread(item.children, item.key);
        }
      }
    }
    spread(tree, 0);
    return arr;
  };
  // 取消点击事件
  onCancel = () => {
    this.props.dispatch({
      type: 'userManageNewM/save',
      payload: {
        cpTreeDate: this.props.oldTreeDate,
      },
    });

    this.onBack('cancel');
  };
  // 确认按钮点击事件
  onOk = () => {
    const {
      user: { currentUser },
      form: { validateFields },
      userManageNewM: { cpTreeDate },
      titleModal,
      oldTreeDate,
    } = this.props;
    let newCpTreeDate = this.flatten2(cpTreeDate);
    let portfolioPermissions = [];
    newCpTreeDate.map((item) => {
      if (item.queryPermission == true || item.operationPermission == true) {
        portfolioPermissions.push(item);
      }
    });
    validateFields(
      [
        'userName',
        'userAccount',
        'userPasswordConfirm',
        'userPassword',
        'userEmail',
        'description',
        'tenant',
        'institutionModels',
        'stationModels',
        'roleModels',
        'autoQueryPortfolio',
        'autoEditPortfolio',
      ],
      (err, fieldsValue) => {
        if (err) return;
        //获取操作员编号数据
        this.OperatorInfoRef?.props.form.validateFields((err, operatorFieldsValue) => {
          if (err) return;
          let operatorData = [];
          operatorFieldsValue?.account?.map((operatorItem) => {
            if (operatorItem.channelIdentify && !!operatorItem.operatorId) {
              operatorData.push(operatorItem);
            }
          });
          let tempInstitution = [];
          let tempStation = [];
          let tempRole = [];
          fieldsValue.institutionModels &&
            fieldsValue.institutionModels.forEach((item) => {
              tempInstitution.push({ id: item });
            });
          fieldsValue.stationModels &&
            fieldsValue.stationModels.forEach((item) => {
              tempStation.push({ id: item });
            });
          fieldsValue.roleModels &&
            fieldsValue.roleModels.forEach((item) => {
              tempRole.push({ id: item });
            });
          const values = {
            name: fieldsValue.userName,
            userAccount: fieldsValue.userAccount,
            userEmail: fieldsValue.userEmail,
            userPassword: fieldsValue.userPassword,
            description: fieldsValue.description,
            createdBy: currentUser.name,
            institutionModels: tempInstitution,
            stationModels: tempStation,
            roleModels: tempRole,
            tenant: fieldsValue.tenant,
            portfolioPermissions: portfolioPermissions,
            autoQueryPortfolio: fieldsValue.autoQueryPortfolio,
            autoEditPortfolio: fieldsValue.autoEditPortfolio,
            operatorNumberList: operatorData, //操作员编号数据
          };
          if (titleModal == '新增用户') {
            this.props.dispatch({
              type: 'userManageNewM/saveTable',
              payload: values,
              callback: (res) => {
                if (res == 'success') {
                  this.onBack('ok');
                  this.props.dispatch({
                    type: 'userManageNewM/save',
                    payload: {
                      cpTreeDate: oldTreeDate,
                    },
                  });
                }
              },
            });
          } else {
            values.id = this.props.editItem.id;
            this.props.dispatch({
              type: 'userManageNewM/saveTable',
              payload: values,
              callback: (res) => {
                if (res == 'success') {
                  this.onBack('ok');
                  this.props.dispatch({
                    type: 'userManageNewM/save',
                    payload: {
                      cpTreeDate: oldTreeDate,
                    },
                  });
                }
              },
            });
          }

          this.setState({
            changeDisable: true,
          });
        });
      },
    );
  };
  // 密码确认校验
  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('userPassword')) {
      callback('两次输入的密码不匹配!');
    } else {
      callback();
    }
  };
  // 租户下拉框change事件
  tenantChange = (value) => {
    // 重置关联组合 全选的勾选状态
    this.setState({
      querySelectAllChecked: false, //关联组合 查询权限 全选控制
      operationSelectAllChecked: false, //关联组合 操作权限 全选控制
    });

    // 重置机构，岗位，角色
    this.props.form.setFieldsValue({
      institutionModels: [],
    });
    this.props.form.setFieldsValue({
      stationModels: [],
    });
    this.props.form.setFieldsValue({
      roleModels: [],
    });
    // 重置关联组合的查询条件
    this.cpRef.props.form.resetFields();
    this.setState(
      {
        isCpReset: true,
      },
      () => {
        this.props.dispatch({
          type: 'userManageNewM/cpTreeDateAll',
          payload: {
            tenant: value,
          },
          callback: (type, res) => {},
        });
      },
    );

    this.setState({
      changeDisable: false, // 租户信息的disable
    });

    this.props.dispatch({
      type: 'userManageNewM/SearchStation',
      payload: {
        tenantId: value,
      },
    });
    this.props.dispatch({
      type: 'userManageNewM/SearchRole',
      payload: {
        tenantId: value,
      },
    });
    this.props.dispatch({
      type: 'userManageNewM/getOrganizationData',
      payload: {
        tenantId: value,
      },
    });
  };
  // 用户基本信息
  baseInfo = () => {
    const {
      form: { getFieldDecorator },
      titleModal,
    } = this.props;
    const formItemLayout2 = {
      labelCol: {
        xs: { span: 2, offset: 0 },
        sm: { span: 2, offset: 0 },
        md: { span: 2, offset: 0 },
        lg: { span: 2, offset: 0 },
        xl: { span: 2, offset: 0 },
        xxl: { span: 2, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 22, offset: 0 },
        sm: { span: 22, offset: 0 },
        md: { span: 22, offset: 0 },
        lg: { span: 22, offset: 0 },
        xl: { span: 22, offset: 0 },
        xxl: { span: 22, offset: 0 },
      },
    };
    return (
      <>
        <SecondHeaderC title='用户基本信息' />
        <Form>
          {/* ***************************第一行****************************** */}
          <Row style={{ marginBottom: '10px' }}>
            <Col span={6}>
              <InputC
                form={this.props.form}
                formItemLayout={formItemLayout}
                dataIndex='userName'
                title={'用户名称'}
                placeholder={'请输入用户名称'}
                rules={[{ required: true, max: 100, message: '请输入用户名称' }]}
                initialValue={titleModal == '编辑用户' ? this.props.editItem.name : ''}
              />
            </Col>
            <Col span={6}>
              <InputC
                form={this.props.form}
                formItemLayout={formItemLayout}
                dataIndex='userAccount'
                title={'用户账号'}
                placeholder={'请输入用户名称'}
                disabled={titleModal == '编辑用户' ? true : false}
                initialValue={titleModal == '编辑用户' ? this.props.editItem.userAccount : ''}
                rules={[{ required: true, max: 100, message: '请输入用户账号' }]}
              />
            </Col>
            {titleModal == '编辑用户' ? null : (
              <Col span={6}>
                <FormItem
                  label={
                    <span>
                      用户密码&nbsp;
                      <Tooltip title='密码长度8-128，且至少包含数字、大写字母、小写字母、特殊字符四类中的三类！'>
                        <QuestionCircleOutlined />
                      </Tooltip>
                    </span>
                  }
                  {...formItemLayout}
                >
                  {getFieldDecorator('userPassword', {
                    rules: [
                      { required: true, message: '请输入密码' },
                      {
                        pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,128}$/,
                        // message: '密码长度8-128，且至少包含数字、大写字母、小写字母、特殊字符四类中的三类！' }
                        message: '输入密码格式不正确！',
                      },
                    ],
                    validateTrigger: 'onBlur',
                  })(<Input placeholder='请输入密码' />)}
                </FormItem>
              </Col>
            )}
            {titleModal == '编辑用户' ? null : (
              <Col span={6}>
                <FormItem
                  label={
                    <span>
                      确认密码&nbsp;
                      <Tooltip title='密码长度8-128，且至少包含数字、大写字母、小写字母、特殊字符四类中的三类！'>
                        <QuestionCircleOutlined />
                      </Tooltip>
                    </span>
                  }
                  {...formItemLayout}
                >
                  {getFieldDecorator('userPasswordConfirm', {
                    rules: [
                      { required: true, message: '请再次输入密码' },
                      {
                        validator: this.checkConfirm,
                      },
                    ],
                    validateTrigger: 'onBlur',
                  })(<Input placeholder='请再次输入密码' />)}
                </FormItem>
              </Col>
            )}
          </Row>
          {/* ***************************第二行****************************** */}
          <Row>
            <Col span={6}>
              <FormItem label='用户邮箱' {...formItemLayout}>
                {getFieldDecorator('userEmail', {
                  initialValue: titleModal == '编辑用户' ? this.props.editItem.userEmail : '',
                  rules: [{ type: 'email', message: '邮箱格式不正确' }],
                })(<Input placeholder='test@example.com' />)}
              </FormItem>
            </Col>
            <Col span={18} style={{ paddingLeft: '1%' }}>
              <FormItem label='描述' {...formItemLayout2}>
                {getFieldDecorator('description', {
                  initialValue: titleModal == '编辑用户' ? this.props.editItem.description : '',
                })(<TextArea style={{ minHeight: 34, width: '97%' }} placeholder='请输入' rows={1} />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </>
    );
  };
  // 租户信息配置
  tenantInfo = () => {
    const {
      userManageNewM: { tenantData, stationData, roleData, organizationData },
      superMan,
      titleModal,
      editItem,
    } = this.props;
    return (
      <>
        <SecondHeaderC title='租户信息配置' />
        <Form>
          <Row>
            {superMan == true ? (
              <Col span={6}>
                <SelectC
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  dataIndex='tenant'
                  dataSource={tenantData}
                  title={'租户选择'}
                  onChange={this.tenantChange}
                  rules={[{ required: true, message: '请选择租户' }]}
                  initialValue={titleModal == '编辑用户' ? this.props.editItem.tenant : undefined}
                  filterOption={(input, option) => {
                    return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
                  }}
                />
              </Col>
            ) : null}

            <Col span={6}>
              <TreeSelectC
                form={this.props.form}
                title='关联机构'
                dataIndex='institutionModels'
                dataSource={organizationData}
                initialValue={titleModal == '编辑用户' ? editItem.editInstitution : undefined}
                disabled={superMan == true ? (titleModal == '编辑用户' ? false : this.state.changeDisable) : false}
                allowClear={true}
                isMultiple={true}
                maxTagCount={0}
                showSearch={true}
                treeDefaultExpandAll={true}
                formItemLayout={formItemLayout}
                filterTreeNode={(inputValue, treeNode) => {
                  return treeNode.props.title.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;
                }}
              />
            </Col>
            <Col span={6}>
              <SelectC
                title='关联岗位'
                form={this.props.form}
                formItemLayout={formItemLayout}
                maxTagCount={0}
                isMultiple={true}
                allowClear={true}
                dataIndex='stationModels'
                dataSource={stationData}
                disabled={superMan == true ? (titleModal == '编辑用户' ? false : this.state.changeDisable) : false}
                initialValue={titleModal == '编辑用户' ? this.props.editItem.editStation : undefined}
                placeholder='请选择关联岗位'
                filterOption={(input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
                }}
              />
            </Col>
            <Col span={6}>
              <SelectC
                title='关联角色'
                form={this.props.form}
                formItemLayout={formItemLayout}
                maxTagCount={0}
                isMultiple={true}
                allowClear={true}
                dataIndex='roleModels'
                dataSource={roleData}
                disabled={superMan == true ? (titleModal == '编辑用户' ? false : this.state.changeDisable) : false}
                initialValue={titleModal == '编辑用户' ? this.props.editItem.editRole : undefined}
                placeholder='请选择关联角色'
                filterOption={(input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
                }}
              />
            </Col>
          </Row>
        </Form>
      </>
    );
  };
  // 查询权限下拉框change事件
  queryPortfolioChange = (e) => {
    const { setFieldsValue } = this.props.form;
    // 如果无查询权限，则操作权限默认为无，且无法选中
    if (e == '1') {
      setFieldsValue({
        autoEditPortfolio: '1',
      });
    }
  };
  // 操作权限下拉框change事件
  editPortfolioChange = (e) => {
    const { setFieldsValue } = this.props.form;
    // 如果有操作权限，则查询权限默认为有
    if (e == '0') {
      setFieldsValue({
        autoQueryPortfolio: '0',
      });
    }
  };
  // 新增产品自动赋权
  permissionInfo = () => {
    const rightsList = [
      { value: '0', title: '是' },
      { value: '1', title: '否' },
    ];
    const {
      form: { getFieldDecorator },
      titleModal,
    } = this.props;
    return (
      <>
        <SecondHeaderC title='新增产品自动赋权' />
        <Form>
          <Row>
            <Col span={6}>
              <FormItem label='查询权限' {...formItemLayout}>
                {getFieldDecorator('autoQueryPortfolio', {
                  initialValue: titleModal == '编辑用户' ? this.props.editItem.autoQueryPortfolio : '1',
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <Select onChange={this.queryPortfolioChange}>
                    {rightsList &&
                      rightsList.map((item, index) => {
                        return (
                          <Select.Option value={item.value} key={index}>
                            {item.title}
                          </Select.Option>
                        );
                      })}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem label='操作权限' {...formItemLayout}>
                {getFieldDecorator('autoEditPortfolio', {
                  initialValue: titleModal == '编辑用户' ? this.props.editItem.autoEditPortfolio : '1',
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <Select onChange={this.editPortfolioChange}>
                    {rightsList &&
                      rightsList.map((item, index) => {
                        return (
                          <Select.Option value={item.value} key={index}>
                            {item.title}
                          </Select.Option>
                        );
                      })}
                  </Select>,
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
        {/* <SecondHeaderC title='操作员配置' /> */}
        <div style={{ marginTop: '16px' }}>
          <Row>
            <Col span={21}>
              <OperatorC
                data={
                  this.props.titleModal == '编辑用户'
                    ? this.props.editItem?.operatorNumberList && this.props.editItem?.operatorNumberList.length > 0
                      ? this.props.editItem?.operatorNumberList || []
                      : []
                    : []
                } //账户信息数组 默认有一个对象
                onRef={(ref) => (this.OperatorInfoRef = ref)}
              />
            </Col>
          </Row>
        </div>
      </>
    );
  };
  /* ********************************关联组合***************************************** */
  // 关联组合权限勾选事件
  handleFieldChange(e, fieldName, key) {
    const {
      userManageNewM: { cpTreeDate },
      dispatch,
    } = this.props;
    const { filteredData } = this.state;
    // 关联组合全部数据
    const newData = depCopy(cpTreeDate);
    const target = findItemByKey(key, newData);

    const filteredNewData = depCopy(filteredData);
    const filteredTarget = findItemByKey(key, filteredNewData);
    if (target) {
      target[fieldName] = e.target.checked;
      dispatch({
        type: 'userManageNewM/save',
        payload: {
          cpTreeDate: newData,
        },
      });
      // 如果 有操作权限，则查询权限肯定为 true
      if (fieldName == 'operationPermission' && e.target.checked == true) {
        target['queryPermission'] = true;
        dispatch({
          type: 'userManageNewM/save',
          payload: {
            cpTreeDate: newData,
          },
        });
      }
      // 如果 无查询权限，则操作权限肯定为 false
      if (fieldName == 'queryPermission' && e.target.checked == false) {
        target['operationPermission'] = false;
        dispatch({
          type: 'userManageNewM/save',
          payload: {
            cpTreeDate: newData,
          },
        });
      }
    }
    // 筛选后的组合data的target
    if (filteredTarget) {
      filteredTarget[fieldName] = e.target.checked;
      this.setState({
        filteredData: filteredNewData,
      });

      if (fieldName == 'operationPermission' && e.target.checked == true) {
        filteredTarget['queryPermission'] = true;
        this.setState({
          filteredData: filteredNewData,
        });
      }

      if (fieldName == 'queryPermission' && e.target.checked == false) {
        filteredTarget['operationPermission'] = false;
        this.setState({
          filteredData: filteredNewData,
        });
      }
    }

    // 判断全选多选框是否勾选
    if (this.state.isCpReset) {
      let queryFlag = false;
      let operationFlag = false;
      if (newData && newData.length) {
        // if (fieldName == 'queryPermission') {
        // 查询权限
        let tempArrQuery = [];
        tempArrQuery = this.generatorValue('queryPermission', newData, tempArrQuery);
        // 是否全选
        queryFlag = this.isEqualData(tempArrQuery);
        this.setState({
          querySelectAllChecked: queryFlag,
        });
        // } else if (fieldName == 'operationPermission') {
        // 操作权限
        let tempArrOperate = [];
        tempArrOperate = this.generatorValue('operationPermission', newData, tempArrOperate);
        // 是否全选
        operationFlag = this.isEqualData(tempArrOperate);
        this.setState({
          operationSelectAllChecked: operationFlag,
        });
        // }
      }
    } else {
      // 查询后 对于筛选后的关联组合的判断
      let filteredQueryFlag = false;
      let filteredOperateFlag = false;
      if (filteredNewData && filteredNewData.length) {
        // if (fieldName == 'queryPermission') {
        // 查询权限
        let tempfQueryArr = [];
        tempfQueryArr = this.generatorValue('queryPermission', filteredNewData, tempfQueryArr);
        // 是否全选
        filteredQueryFlag = this.isEqualData(tempfQueryArr);
        this.setState({
          querySelectAllChecked: filteredQueryFlag,
        });
        // } else if (fieldName == 'operationPermission') {
        let tempfOperateArr = [];
        tempfOperateArr = this.generatorValue('operationPermission', filteredNewData, tempfOperateArr);
        // 是否全选
        filteredOperateFlag = this.isEqualData(tempfOperateArr);
        this.setState({
          operationSelectAllChecked: filteredOperateFlag,
        });
        // }
      }
    }
  }
  // 关联组合页码变化事件
  cpTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState({
      cpCurrentPage: current,
      cpNumInPage: pageSize,
    });
  };
  // 递归树形结构，根据msg查找包含msg的节点
  generatorCpData = (msg, treeData, arr) => {
    for (let item of treeData) {
      if (item.portfolioCode.includes(msg) || item.portfolioName.includes(msg)) {
        arr.push(item);
      } else if (item.children != null && item.children.length) {
        this.generatorCpData(msg, item.children, arr);
      }
    }
    return arr;
  };
  // 递归树形结构，更改所有某属性的值
  generatorChangeItem = (value, valueName, treeData) => {
    for (let item of treeData) {
      if (item.children != null && item.children.length) {
        this.generatorChangeItem(value, valueName, item.children);
      }
      item[valueName] = value;
    }
    return treeData;
  };

  // 递归树形结构，判断所有数据的同一属性值是否相等 遍历所有该属性值,放在数组中返回
  generatorValue = (valueName, treeData, result) => {
    for (let item of treeData) {
      if (item.children != null && item.children.length) {
        this.generatorValue(valueName, item.children, result);
      }
      result.push(item[valueName]);
    }
    return result;
  };
  // 判断数组所有值是否都相等,相等返回a[0]即第一个元素,不相等返回false
  isEqualData = (tempArr) => {
    let firstData = tempArr[0];
    let isEquality = tempArr.every((val) => {
      return val === firstData;
    });
    if (isEquality) {
      return firstData;
    } else {
      return false;
    }
  };
  // 关联组合搜索事件
  relateSearchChange = (e) => {
    const {
      userManageNewM: { cpTreeDate },
    } = this.props;
    let arr = [];
    let msg = e.relateName;
    if (msg) {
      let resultData = this.generatorCpData(msg, cpTreeDate, arr);
      this.setState({
        filteredData: resultData,
      });
    }
  };

  // 关联组合-查询权限全选事件
  querySelectAll = (e, type) => {
    const {
      userManageNewM: { cpTreeDate },
    } = this.props;
    if (type == 'queryPermission') {
      // 查询权限全选框勾选
      this.setState(
        {
          querySelectAllChecked: e,
        },
        () => {
          if (e == false) {
            // 若无查询权限,则操作权限也无
            this.querySelectAll(false, 'operationPermission');
          }

          if (this.state.isCpReset) {
            // 如果没有查询,则更改cpTreeDate
            this.props.dispatch({
              type: 'userManageNewM/save',
              payload: {
                cpTreeDate: this.generatorChangeItem(e, 'queryPermission', cpTreeDate),
              },
            });
          } else {
            // 如果有查询,则更改filteredData
            let tempArr = this.generatorChangeItem(e, 'queryPermission', this.state.filteredData);
            this.setState(
              {
                filteredData: tempArr,
              },
              () => {
                this.props.dispatch({
                  type: 'userManageNewM/save',
                  payload: {},
                });
              },
            );
          }
        },
      );
    } else if (type == 'operationPermission') {
      // 操作权限全选框勾选
      this.setState(
        {
          operationSelectAllChecked: e,
        },
        () => {
          if (e == true) {
            // 若有操作权限,则查询权限也有
            this.querySelectAll(true, 'queryPermission');
          }

          if (this.state.isCpReset) {
            // 如果没有查询,则更改cpTreeDate
            this.props.dispatch({
              type: 'userManageNewM/save',
              payload: {
                cpTreeDate: this.generatorChangeItem(e, 'operationPermission', cpTreeDate),
              },
            });
          } else {
            // 如果有查询,则更改filteredData
            let tempArr = this.generatorChangeItem(e, 'operationPermission', this.state.filteredData);
            this.setState(
              {
                filteredData: tempArr,
              },
              () => {
                this.props.dispatch({
                  type: 'userManageNewM/save',
                  payload: {},
                });
              },
            );
          }
        },
      );
    }
  };

  // 关联组合-查询权限表头title 自定义返回内容
  queryTitle = (type) => {
    const { defaultQuery, defaultOperation } = this.props;
    return (
      <div>
        <span style={{ marginRight: '10px' }}>{type == 'queryPermission' ? '查询权限' : '操作权限'}</span>
        <Checkbox
          defaultChecked={type == 'queryPermission' ? defaultQuery : defaultOperation}
          checked={type == 'queryPermission' ? this.state.querySelectAllChecked : this.state.operationSelectAllChecked}
          onChange={(e) => {
            this.querySelectAll(e.target.checked, type);
          }}
        ></Checkbox>
      </div>
    );
  };

  // 关联组合
  relatedGroup = () => {
    const {
      userManageNewM: { cpTreeDate },
    } = this.props;
    const cpcolumns = [
      {
        title: '组合代码',
        dataIndex: 'portfolioCode',
        key: 'portfolioCode',
        width: 400,
      },
      {
        title: '组合名称',
        dataIndex: 'portfolioName',
        key: 'portfolioName',
        width: 400,
      },
      {
        title: this.queryTitle('queryPermission'),
        dataIndex: 'queryPermission',
        key: 'queryPermission',
        editable: true,
        render: (text, record, index) => {
          return (
            <Checkbox
              checked={text}
              onChange={(e) => {
                this.handleFieldChange(e, 'queryPermission', record.key);
              }}
            >
              {' '}
            </Checkbox>
          );
        },
      },
      {
        title: this.queryTitle('operationPermission'),
        dataIndex: 'operationPermission',
        key: 'operationPermission',
        render: (text, record, index) => {
          return (
            <Checkbox checked={text} onChange={(e) => this.handleFieldChange(e, 'operationPermission', record.key)}>
              {' '}
            </Checkbox>
          );
        },
      },
    ];
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'relateName',
          title: '名称或代码',
          type: DATA_ENTRY.INPUT,
          placeholder: '请输入组合名称或代码进行模糊搜索',
          allowClear: true,
          showSearch: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        if (e && JSON.stringify(e) != '{}') {
          this.setState(
            {
              isCpReset: false,
            },
            () => {
              this.relateSearchChange(e);
            },
          );
        }
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          isCpReset: true,
        });
      },
    };
    return (
      <>
        <SecondHeaderC title='关联组合' />
        <div style={{ marginBottom: '16px' }}>
          <AdvancedSearch onRef={(ref) => (this.cpRef = ref)} {...searchProps} />
        </div>
        <Spin
          spinning={
            this.props.titleModal == '新增用户'
              ? this.props.loading.effects['userManageNewM/cpTreeDateAll'] == true
              : this.props.loading.effects['userManageNewM/cpTreeDate'] == true
          }
        >
          <TableC
            columns={cpcolumns}
            pagination={true}
            total={this.state.cpTotal}
            current={this.state.cpCurrentPage}
            pageSize={this.state.cpNumInPage}
            onChange={this.cpTableChange}
            scroll={{ y: 320 }}
            rowKey={(record) => record.key}
            dataSource={this.state.isCpReset ? cpTreeDate : this.state.filteredData}
          />
        </Spin>
      </>
    );
  };

  /* ********************************关联组合***************************************** */
  render() {
    const { titleModal } = this.props;
    return (
      <div>
        <FixedButtonC
          topHtml={
            <>
              <FirstHeaderC title={titleModal} />
              <Row style={{ marginBottom: '10px' }}>
                <Col>{this.baseInfo()}</Col>
              </Row>
              <Row style={{ marginBottom: '10px' }}>
                <Col>{this.tenantInfo()}</Col>
              </Row>
              <Row style={{ marginBottom: '10px' }}>
                <Col>{this.permissionInfo()}</Col>
              </Row>
              <Row style={{ marginBottom: '10px' }}>
                <Col>{this.relatedGroup()}</Col>
              </Row>
            </>
          }
          bottomHtml={
            <div className={myStyle.borderLine}>
              <PrimaryC
                title='确定'
                onClick={this.onOk}
                loading={
                  this.props.loading.effects['userManageNewM/cpTreeDateAll'] == true ||
                  this.props.loading.effects['userManageNewM/cpTreeDate'] == true ||
                  this.props.loading.effects['userManageNewM/saveTable'] == true
                }
              />
              <PrimaryGhostC title='取消' onClick={this.onCancel} />
            </div>
          }
        ></FixedButtonC>
      </div>
    );
  }
}
